import React, { Component } from "react";
import PropTypes from "prop-types";
import moment from "moment";
import Select from "../../tools/Select";
import { getCalendarStart } from "../../util/util";
import { MONTH_TBALE_COL, MONTH_TBALE_ROW } from '../../constants/constant';
import "./index.scss";

//  日历的功能部分
export default class CalendarOperation extends Component {
  onYearOrMonthChange(value, isMonthChange = true) {
    const { currentDate, changeCurrentDate, onDateChange } = this.props;
    let newDate;
    if (isMonthChange) {
      newDate = moment(currentDate).month(value);
    } else {
      newDate = moment(currentDate).year(value);
    }
    changeCurrentDate(newDate);
    if (typeof onDateChange === "function") {
      const calendarStart = getCalendarStart(newDate);
      const monStart = moment(newDate).startOf("month");
      const calendarEnd = moment(calendarStart).add(MONTH_TBALE_ROW * MONTH_TBALE_COL - 1, "day");

      onDateChange({
        start: calendarStart,
        end: calendarEnd,
        current: monStart
      });
    }
  }

  render() {
    const { currentDate} = this.props;
    const year = moment(currentDate).year();
    const month = moment(currentDate).month();
    const years = Array.from(Array(20)).map((value, index) => {
      return year - 10 + index;
    });
    const months = Array.from(Array(12)).map((item, index) => {
      const date = moment(currentDate).month(index);
      return {
        label: date.format("MMM"),
        value: date.month()
      };
    });
    return (
      <div className="rc_calendar-operation">
        <div className="rc_calendar-operation_right-content">
          <Select
            dataSource={years}
            defaultValue={year}
            onChange={value => {
              this.onYearOrMonthChange.bind(this)(value, false);
            }}
          />
          <Select
            dataSource={months}
            defaultValue={month}
            onChange={value => {
              this.onYearOrMonthChange.bind(this)(value);
            }}
          />
        </div>
      </div>
    );
  }
}

CalendarOperation.propTypes = {
  currentDate: PropTypes.object.isRequired
};
